<!-- 排序状态组件 -->
<script setup lang="ts">
import mpMixin from "@/components/libs/mixin/mpMixin";
defineOptions(mpMixin);
const ASC = "Asc";
const DESC = "Desc";

type Order = typeof ASC | typeof DESC | undefined | "";
const props = withDefaults(
  defineProps<{
    /**是否可 order by 多个 */
    multiple?: boolean;
    /**order by 排序字段*/
    name: string;
    /**排序字段结果集合；多个用,隔开 */
    field: string | undefined;
    /**排序方式 Desc | Asc；多个用,隔开 */
    order: string | undefined;
  }>(),
  {
    order: "",
    field: "",
  }
);

const orderArr = computed({
  get() {
    if (!props.order.length) return [];
    return props.order.split(",");
  },
  set(v) {
    emit("update:order", v.join(","));
  },
});
const fieldArr = computed({
  get() {
    if (!props.field.length) return [];
    return props.field.split(",");
  },
  set(v) {
    emit("update:field", v.join(","));
  },
});

const nowIndex = computed<number>(() => {
  if (!props.field || !props.order || !props.name) return -1;
  const fields = fieldArr.value;
  return fields.findIndex((v) => v === props.name);
});

const nowOrder = computed<Order>(() => {
  const index = nowIndex.value;
  if (index === -1) return;
  const order = orderArr.value[index];
  if (!order) return;
  return order as any;
});

function giveNot(key: Order) {
  if (!key || key === "Desc") return ASC;
  return DESC;
}

const emit = defineEmits<{
  "update:field": [v: string | undefined];
  "update:order": [v: string | undefined];
  change: [v: string | undefined];
}>();

function changeSort() {
  const newOrder = giveNot(nowOrder.value);
  if (!props.multiple) {
    emit("update:field", props.name);
    emit("update:order", newOrder);
    emit("change", newOrder);
    return;
  }
  const index = nowIndex.value;
  const _fieldArr = [...fieldArr.value];
  const _orderArr = [...orderArr.value];
  if (index === -1) {
    _fieldArr.push(props.name);
    _orderArr.push(newOrder);
  } else {
    _orderArr[index] = newOrder;
  }

  fieldArr.value = _fieldArr;
  orderArr.value = _orderArr;
  emit("change", newOrder);
}
</script>

<template>
  <view @tap="changeSort" class="CoSortControl inline-flex items-stretch">
    <slot> </slot>
    <view class="CoSortControl_marker ml-1 flex flex-col">
      <view class="mt-auto" style="margin-bottom: -2.5px">
        <wd-icon
          name="arrow-up"
          size="12px"
          :class="ASC ? '!c-jun-primary' : ''"
        />
      </view>
      <view class="mb-auto">
        <wd-icon
          name="arrow-down"
          size="12px"
          :class="DESC ? '!c-jun-primary' : ''"
        />
      </view>
    </view>
  </view>
</template>

<style lang="scss" scoped>
.CoSortControl {
  .CoSortControl_marker {
    transform: scaleY(0.7);
    .uv-icon {
      border: none !important;
    }
  }
}
</style>
